function anaOut = Dac(decIn, vRef, NOB, errit)

% User: jacobw
% Project name: stuck
% Project area: /proj/es/shekes/stuck
%
% Department of Electrical Engineering
% Linkoping University 
%
% Updated by Armin Jalili
% Department of Electrical and Computer Engineering
% Isfahan University of Technology
% 
% Wed June 5 2013
%
    
% Assume range is from -Vref to vRef

% Assume decIn is in offset binary format   
    scale     = 2*(vRef / (2^NOB));
    if (nargin == 4) 
        binVector = errit(1:(end-1));        
        offset    = errit(end);
    else
        binVector = (2.^((NOB-1):-1:0)');
        offset    = -vRef + scale / 2;
    end
    
    % Strings must be generated as matrix instead...
    %binIn = dec2bin(decIn, NOB); %a bit slow...
    anaOut    = offset;
    decIn_ = decIn;
    for m = 1:NOB;
        bit_ = decIn_ >= 2 ^ (NOB - m);
        anaOut = anaOut + bit_ * scale * binVector(m);
                % str2num(binIn(:,m))*scale*binVector(m);
        %                 str2num(binIn(:,m))*scale*2^(NOB-m);
        decIn_ = decIn_ - bit_ * 2 ^ (NOB - m); 
    end
    
